Snail(function($, win, doc, undefined){

	/**
	 *  默认值：/seeyon
	 */
	var appBasePath = (function(){
		
		var path = location.pathname;
		
		return path.substring(0, path.indexOf('/', 1));
	})();
	
	function getTransParams(){
		
		var ctrlDialog = win.parentDialogObj && win.parentDialogObj["ctrlDialog"];
		
		return ctrlDialog.getTransParams();
	}
	
	function getTableInfo(){
		
		return getTransParams().formBaseInfo.formBaseInfo.tableInfo;
	}
	
	function getConfig(key, defaultValue){
		
		var params = getTransParams().params;
		
		if(null == params){
			return defaultValue;
		}
		
		return params[key] || defaultValue;
	}
		
	function getAllViewAuthList(){
		
		return top.document.getElementById('formdesign-frame').contentWindow.allViewAuthList;
	}
	
	function getFormCode(){
		
		var formCode = top.document.getElementById('formdesign-frame').contentWindow.$("#formCode").val();
		
		return formCode ? formCode.trim() : null;
	}
	

	var groovyMirror = (function (){

		var aesPwd = 'Xxeicq3gknHJEsZR';
		var editor = null;
		var script = null;

		return {
			init: function(){
				
				setTimeout(function(){
					
					if(null != editor){
						
						$.setCSS(editor.getWrapperElement(), {display: 'block'});
						
						return;
					}
					
					if($.isBlank(script)){
												
						$.setEleValue('#script_content', script = (function(){
							
							var scriptTxt = ['#!/snail/common/utils groovy BTN_SCRIPT_' + $.random20L()];
							scriptTxt.push('');
							scriptTxt.push('import com.seeyon.ctp.common.AppContext;');
							scriptTxt.push('import com.seeyon.apps.snail.APPLogger;');
							scriptTxt.push('import com.seeyon.apps.snail.common.MessageHepler;');
							scriptTxt.push('');
							scriptTxt.push('import snail.common.ClassHelper;');
							scriptTxt.push('import snail.common.ServiceException;');
							scriptTxt.push('import snail.common.utils.StringHelper;');
							scriptTxt.push('import snail.common.utils.JSONHelper;');
							scriptTxt.push('import snail.common.utils.DateHelper;');
							scriptTxt.push('import snail.common.utils.IDHelper;');
							scriptTxt.push('import snail.common.utils.db.DBHelper;');
							scriptTxt.push('import snail.common.utils.db.DataSourceHelper;');
							scriptTxt.push('import snail.common.web.HTTPHelper;');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('/**');
							scriptTxt.push(' * 自定义脚本（Groovy）');
							scriptTxt.push(' * ');
							scriptTxt.push(' * @author: snail(snail_email@163.com)');
							scriptTxt.push(' */');
							scriptTxt.push('static main(String[] args){');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('    return \'看到提示了吗？\';');
							scriptTxt.push('}');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('/** ******************************* 以下为共公函数 ******************************* */');
							scriptTxt.push('include seeyon.common.groovy;');
							scriptTxt.push('');
							
							return scriptTxt.join('\r\n');
						})());
						
					}else{
						
						$.setEleValue('#script_content', script);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#script_content'), {
						mode: 'text/x-groovy',
						theme: "darcula",
						lineNumbers: true,
						lineWrapping: true,
						indentUnit: 4,
						extraKeys: {
							'Ctrl': 'autocomplete'
						},
						hintOptions: {
							completeSingle: false,
							hint: $.codemirror.groovyShowHint,
							word: {
								__WORD_LIST__: [
									'getObjBySQL(sqlStr, closure, nodata_closure=null)', 'getObjBySQL(sqlStr, args, closure, nodata_closure)', 
									'getListBySQL(sqlStr, closure, nodata_closure=null)', 'getListBySQL(sqlStr, args, closure, nodata_closure)',
									'getSQLClient()', 'sendMessage(txt, receiver=null)', 'logger(txt)', 'GLOBALS(key, value=null)', 'NVL(obj, Object... obj2)'
								]
							}
						}
					});
					
					editor.on('keypress', function(){
						//编译器内容更改事件
						editor.showHint();
					});
					
					editor.refresh();
					
				}, 200);
			},
			setValue: function(_script){
				
				script = $.aes_decrypt((_script ? decodeURIComponent(_script) : script), aesPwd);
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(script);
			},
			getValue: function(){
				return $.aes_encrypt((editor ? editor.getValue() : script), aesPwd);
			},
			getCode: function(){
				
				if(!$.isBlank(script)){
					
					var scriptMark = script.match(/\#\!\/snail\/common\/utils\s+groovy\s+[a-zA-Z_0-9]+/);
					
					if(null != scriptMark && 0 < scriptMark.length){
						
						scriptMark = scriptMark[0];
						scriptMark = scriptMark.substring(scriptMark.indexOf('groovy') + 7);
						scriptMark = scriptMark.replace(/\s+/g, '');
						
						return scriptMark;
					}
				}
				
				return null;
			},
			close: function(){
				editor && $.setCSS(editor.getWrapperElement(), {display: 'none'});
			}
		}
	})();
	
	
	/**
	 * 初始化窗口
	 */
	function initWindow(){
		
		var dialog = $.getElement('div[laytype="dialog"]', 0, window.parent.document);
				
		var width = window.screen.width || window.screen.availWidth;
		
		if(1440 < width){
			
			$.setCSS(dialog, {
				width: 'calc(100% - 200px)', height: 'calc(100% - 100px)',
				top: '50px', left: '100px'
			});
			
		}else{
			
			$.setCSS(dialog, {
				width: 'calc(100% - 50px)', height: 'calc(100% - 20px)',
				top: '10px', left: '25px'
			});
		}

		var dialogWindow = $.getElement('div[laytype="dialog"]>div:nth-child(2)', 0, window.parent.document);
		
		$.setCSS(dialogWindow, {
			height: 'calc(100% - 105px)'
		});
		
		dialogWindow = $.getElement('div[laytype="dialog"]>div:nth-child(2)>iframe', 0, window.parent.document);
		
		$.setCSS(dialogWindow, {
			height: '100%'
		});
		
		var dialogTitle = $.getElement('div[laytype="dialog"]>div:first-child', 0, window.parent.document);
		
		$.cleanHtml(dialogTitle);
		$.appendHtml(dialogTitle, '脚本编辑器');
	}
		
	/**
	 * 初始化页面
	 */
	(function(){
		
		initWindow();
		
		groovyMirror.init();
		groovyMirror.setValue(getConfig('script'));
		
	})();
	
	
	/**
	 *	保存返回数据
	 */
	win['OK'] = function () {
						
		return {
			valid: true,
			data: {
				scriptCode: groovyMirror.getCode(),
				script: groovyMirror.getValue()
			}
		};
	};
	
});